package com.limingru.newbee.config;

import com.limingru.newbee.common.NewBeeMallException;
import com.limingru.newbee.common.ServiceResultEnum;
import com.limingru.newbee.util.Result;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@RestControllerAdvice
public class NewBeeMallExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object bindException(MethodArgumentNotValidException e) {
        Result result = new Result();
        result.setResultCode(510);
        BindingResult bindingResult = e.getBindingResult();
        result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        return result;
    }

    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e) {
        Result result = new Result();
        result.setResultCode(500);
        if (e instanceof NewBeeMallException) {
            String message = e.getMessage();
            result.setMessage(message);
            if (message.equals(ServiceResultEnum.NOT_LOGIN_ERROR.getText()) || message.equals(ServiceResultEnum.LOGIN_HAS_EXPIRED.getText()) || message.equals((ServiceResultEnum.USER_IS_NULL.getText()))) {
                result.setResultCode(416);
            }
        } else {
            e.printStackTrace();
            result.setMessage(e.getMessage());
        }
        return result;
    }
}
